﻿using AnyLink.PosClient.View;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;

namespace AnyLink.PosClient
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        [DllImport("user32.dll")]
        public static extern int MessageBoxTimeoutA(IntPtr hWnd, string msg, string Caps, int type, int Id, int time);
        Mutex mutex;
        /// <summary>
        /// Services
        /// </summary>
        public IServiceProvider Services { get; }
        /// <summary>
        /// Current app
        /// </summary>
        public static  new  App Current => (App)Application.Current;
        public App()
        {
            Services = ConfigureServices();

            
        }
        /// <summary>
        /// Configure services
        /// </summary>
        /// <returns></returns>
        private static IServiceProvider ConfigureServices()
        {
            // Configure services
            var services = new ServiceCollection();
            services.AddView();
            services.AddViewModel();
            services.AddLogging();
            return services.BuildServiceProvider();
        }
        /// <summary>
        /// On startup
        /// </summary>
        /// <param name="e"></param>
        protected override void OnStartup(StartupEventArgs e)
        {
            mutex = new Mutex(true, Process.GetCurrentProcess().ProcessName);
            if (!mutex.WaitOne(TimeSpan.Zero, true))
            {
                MessageBoxTimeoutA((IntPtr)0, "当前程序已经在运行中", "提示", 0, 0, 1000);
                System.Environment.Exit(0);
                return;
            }

            try
            {
                base.OnStartup(e);

                var loginWindow = Services.GetRequiredService<LoginWin>();
                loginWindow.Show();
            }
            finally
            {
                // 释放互斥锁
                mutex.ReleaseMutex();

            }
        }
    }
}
